package com.example.demo.service.Impl;

import com.example.demo.mapper.LevelMapper;
import com.example.demo.service.LevelService;
import com.example.demo.vo.LevelVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;


@Service
public class LevelServiceImpl implements LevelService {
    @Autowired
    private LevelMapper levelMapper;

    @Override
    public List<LevelVo> getLevelList() {
        List<LevelVo> levelList = levelMapper.getLevelList();

        for (LevelVo levelVo : levelList) {
            levelVo.setRate(levelVo.getValue1() / levelVo.getValue2());
            levelVo.setRateString(levelVo.getValue1() / levelVo.getValue2() * 100 + "%");
        }
        levelList.sort(Comparator.comparingDouble(LevelVo::getRate).reversed());
        if (!levelList.isEmpty()) {
            levelList.get(0).setLevel(1);
            for (int i = 1; i < levelList.size(); i++) {
                LevelVo current = levelList.get(i);
                LevelVo next = levelList.get(i - 1);
                if (Math.abs(current.getRate() - next.getRate()) < 1e-9) {
                    current.setLevel(next.getLevel());
                } else {
                    current.setLevel(i + 1); // 索引转排名（从1开始）
                }
            }
        }
        return levelList;
    }
}
